package org.m8.auth.model;

import com.querydsl.core.types.Projections;
import com.querydsl.core.types.QBean;
import org.m8.auth.model.qentity.QOauth2RefreshToken;
import org.m8.dba.config.SQLQueryFactoryManager;
import org.m8.dba.transaction.M8Transactional;
import org.springframework.stereotype.Component;

/**
 * dao
 *
 * @author yidanjun
 * @date 2024/9/4
 **/
@Component
@M8Transactional
public class OAuth2RefreshTokenDao {
    public final QBean<OAuth2RefreshTokenDO> oAuth2RefreshTokenDOQBean = Projections.bean(OAuth2RefreshTokenDO.class, QOauth2RefreshToken.m8Oauth2RefreshToken.all());

    /**
     * 新增
     */
    public long inert(OAuth2RefreshTokenDO oAuth2RefreshTokenDO) {
        return SQLQueryFactoryManager.getQueryFactory()
                .insert(QOauth2RefreshToken.m8Oauth2RefreshToken)
                .populate(oAuth2RefreshTokenDO)
                .execute();
    }

    /**
     * 根据refreshToken查询
     */
    public OAuth2RefreshTokenDO getByRefreshToken(String refreshToken) {
        return SQLQueryFactoryManager.getQueryFactory()
                .select(oAuth2RefreshTokenDOQBean)
                .from(QOauth2RefreshToken.m8Oauth2RefreshToken)
                .where(QOauth2RefreshToken.m8Oauth2RefreshToken.refreshToken.eq(refreshToken))
                .fetchOne();
    }

    /**
     * 根据refreshToken删除
     * @param refreshToken
     * @return
     */
    public long deleteByRefreshToken(String refreshToken) {
        return SQLQueryFactoryManager.getQueryFactory()
                .delete(QOauth2RefreshToken.m8Oauth2RefreshToken)
                .where(QOauth2RefreshToken.m8Oauth2RefreshToken.refreshToken.eq(refreshToken))
                .execute();
    }

    /**
     * 根据id删除
     */
    public long deleteById(String id) {
        return SQLQueryFactoryManager.getQueryFactory()
                .delete(QOauth2RefreshToken.m8Oauth2RefreshToken)
                .where(QOauth2RefreshToken.m8Oauth2RefreshToken.id.eq(id))
                .execute();
    }
}
